package com.yisen.dasan.util;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTCreator;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.auth0.jwt.interfaces.Verification;

import java.util.Calendar;
import java.util.Map;

/**
 * @AuthorList: LiuYiSen
 * @Date: 2020/11/28 22:34
 */
public class JWTUtils {
    private static final String SING = "#tgg%%^h8^9nig(jig(i&___098f78sdfoiug889()lkjdfo";

    /**
     * 生成令牌
     * @param map
     * @return
     */
    public static String getToken(Map<String,String> map){
        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.DATE, 7);

        JWTCreator.Builder builder = JWT.create();
        map.forEach((k,v)->{ // 添加 payload 值
            builder.withClaim(k, v);
        });
        String token = builder.withExpiresAt(calendar.getTime()).sign(Algorithm.HMAC256(SING));// 设置token过期时间并且 token 构建
        return token;
    }

    public static DecodedJWT verify(String token){
        JWTVerifier verifier = JWT.require(Algorithm.HMAC256(SING)).build();
        DecodedJWT verify = verifier.verify(token);
        return verify;
    }
}
